﻿using SuperSimpleWebshop.Common;
using SuperSimpleWebshop.Domain;
using SuperSimpleWebshop.Domain.Interfaces;
using SuperSimpleWebshop.Domain.Repositories;
using umbraco;

namespace SuperSimpleWebshop.Payment.PayPal
{
    /// <summary>
    /// Handles the response from the payment provider
    /// </summary>
    public class PayPalPaymentResponseHandler : IPaymentResponseHandler
    {
        #region IPaymentResponseHandler Members
        IOrderRepository _OrderRepository = new OrderRepository();

        /// <summary>
        /// Gets the payment provider name
        /// </summary>
        /// <returns>Name of the payment provider</returns>
        public string GetName()
        {
            return "PayPal";
        }

        /// <summary>
        /// Handles the response
        /// </summary>
        public string HandlePaymentResponse()
        {
            // PayPal POSTS some values
            string paymentStatus = library.Request("payment_status");

            // Get identifier created with the RequestHandler
            string transactionId = library.Request("custom");

            // Match  identifier to order
            var order = this._OrderRepository.GetOrderByPaymentTransactionId(transactionId);

            // Check for match
            if (order != null)
            {
                // Get statusses from payment provider Response
                switch (paymentStatus)
                {
                    case "Completed":
                        order.OrderInfo.Status = OrderStatus.Ready_for_Dispatch;
                        order.Save();
                        break;
                    case "Failed":
                        order.OrderInfo.Status = OrderStatus.Payment_Failed;
                        order.Save();
                        break;
                    case "Denied":
                        order.OrderInfo.Status = OrderStatus.Payment_Failed;
                        order.Save();
                        break;
                    case "Pending":
                        order.OrderInfo.Status = OrderStatus.Waiting_for_Payment;
                        order.Save();
                        break;
                }
            }

            return null;
        }
        #endregion
    }
}
